//
//  AppDelegate.swift
//  Your Lover AI
//
//  Created by 阿忠 on 2024/6/18.
//

import UIKit
import CoreData
import IQKeyboardManagerSwift
import SwiftyStoreKit
import FacebookCore
import FirebaseCore
import FirebaseFirestore
import FirebaseAuth
import FirebaseAnalytics
import GoogleMobileAds
import FirebaseRemoteConfig
import PAGAdSDK
import FirebaseCrashlytics
import StoreKit

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    
    var remoteConfig: RemoteConfig!
    
    let myNotificationName = Notification.Name("MyNotificationName")
    
    var rewardedView: YLALodaingView! = nil
    
    //用来判断是否切换到后台
    var shouldShowFixedView = false
    
    var timer: Timer?
    
    
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        
        // 读取存储的 UUID
        if let storedUUID = KeychainManager.shared.retrieveUUID(){
            
            //54DEB7D3-46B0-4AAF-A106-D10780D4F138
            print("Retrieved UUID from Keychain: \(storedUUID)")
            
        }else{
            if let generatedUUID = KeychainManager.shared.generateAndStoreUUID() {
                print("Generated and stored UUID: \(generatedUUID)")
            }
        }
        
        
        
        //Admob
        GADMobileAds.sharedInstance().start(completionHandler: nil)
        
        //FaceBook
        ApplicationDelegate.shared.application(
            application,
            didFinishLaunchingWithOptions: launchOptions
        )
        
        //FirebaseCore
        FirebaseApp.configure()
        Crashlytics.crashlytics().setCrashlyticsCollectionEnabled(true)
        Crashlytics.initialize()
        Analytics.initialize()
        
        
        //Firebase Remote Config更新字段
        self.FirebaseRemoteConfig()
        
        timer = Timer.scheduledTimer(withTimeInterval: 60.0, repeats: true) { (timer) in
            // 在这里编写你想要每分钟执行一次的代码
            print("定时器执行：\(Date())")
            self.FirebaseRemoteConfig()
        }
        
        
        //pangle
        //        self.setupBUAdSDK()
        
        IQKeyboardManager.shared.enable = true
        
        //没有进入首页 不可以弹开屏广告
        let userDefaults = UserDefaults.standard
        userDefaults.set(false, forKey: "tostOpenAd")
        
        // 注册监听器以接收通知
        NotificationCenter.default.addObserver(self, selector: #selector(receiveNotification(_:)), name: myNotificationName, object: nil)
        
        SwiftyStoreKit.completeTransactions(atomically: true) { purchases in
            for purchase in purchases {
                switch purchase.transaction.transactionState {
                case .purchased, .restored:

                    if purchase.needsFinishTransaction {
                        // Deliver content from server, then:
                        SwiftyStoreKit.finishTransaction(purchase.transaction)
                    }
                    
                    // Unlock content
                case .failed, .purchasing, .deferred:
                    break // do nothing
                }
            }
        }
        
        //校验订阅是否过期
        
        if checkIfCanMakePayments() {
            self.renstorSet()
        }
        
        
//        SwiftyStoreKit.purchaseProduct(productId) { result in
//            switch result {
//            case .success(let purchase):
//                print("Purchase Success: \(purchase.productId)")
//                // 获取收据数据
//                if let receiptData = SwiftyStoreKit.localReceiptData {
//                    let receiptString = receiptData.base64EncodedString(options: [])
//                    // 发送 receiptString 到服务器进行验证
//                    validateReceipt(receiptString)
//                } else {
//                    print("Receipt data not found.")
//                }
//            case .error(let error):
//                print("Purchase Failed: \(error)")
//            }
//        }

        
        //        Analytics.logEvent("测试上传", parameters: [
        //            "button_name": "my_button",
        //            "button_location": "home_screen"
        //        ])
        //
        
        //区分是否首次进入
        if let isSet = UserDefaults.standard.string(forKey: "user_set") {
            // isSet 有一个值，进入主页
            print("User gender is: \(isSet)")
            let startVc = YLALoadIngViewController()
            let nav_0 = UINavigationController(rootViewController: startVc)
            let tabBarController = UITabBarController()
            tabBarController.viewControllers = [nav_0]
            tabBarController.tabBar.tintColor = UIColor.white
            
            tabBarController.tabBar.unselectedItemTintColor = UIColor.gray
            self.window?.rootViewController = tabBarController
            
        } else {
            let startVc = YLAStartViewControll()
            let nav_0 = UINavigationController(rootViewController: startVc)
            let tabBarController = UITabBarController()
            tabBarController.viewControllers = [nav_0]
            tabBarController.tabBar.tintColor = UIColor.white
            
            tabBarController.tabBar.unselectedItemTintColor = UIColor.gray
            self.window?.rootViewController = tabBarController
        }
        
        return true
    }
    
    
    // 当接收到通知时调用的方法
    @objc func receiveNotification(_ notification: Notification) {
        if let userInfo = notification.userInfo, let value = userInfo["key"] as? String {
            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                AppOpenAdManager.shared.showAdIfAvailable()
                print("这条消息在1秒后打印")
            }
            
        }
    }
    
    
    func setupBUAdSDK(){
        //        PAGConfig *config = [PAGConfig shareConfig];
        let config = PAGConfig.share()
        config.appID = "8455135"
        config.appLogoImage = UIImage(named: "logo")
    }
    
    func FirebaseRemoteConfig(){
        
        remoteConfig = RemoteConfig.remoteConfig()
        let settings = RemoteConfigSettings()
        settings.minimumFetchInterval = 0
        remoteConfig.configSettings = settings
        
        remoteConfig.setDefaults(fromPlist: "RemoteConfigDefaults")
        
        // 添加配置更新监听器
        remoteConfig.addOnConfigUpdateListener { configUpdate, error in
            guard let configUpdate = configUpdate, error == nil else {
                self.displayError(error)
                return // 实际上在这里不是必需的，因为闭包不期望返回值
            }
            
            print("Updated keys: \(configUpdate.updatedKeys)")
            
            self.remoteConfig.activate { changed, error in
                guard error == nil else {
                    self.displayError(error)
                    return // 如果这是在一个需要返回值的闭包中，这是必需的
                }
                // 激活成功
            }
        }
        
        // 尝试获取最新配置
        fetchAndActivateRemoteConfig()
    }
    
    // 获取并激活 Remote Config
    func fetchAndActivateRemoteConfig() {
        remoteConfig.fetch(withExpirationDuration: 3600) { [weak self] status, error in
            guard let self = self else { return }
            
            if let error = error {
                print("Error fetching remote config: \(error)")
                return
            }
            
            if status == RemoteConfigFetchStatus.success {
                print("Remote config fetched successfully!")
                self.remoteConfig.activate { [weak self] changed, error in
                    guard let self = self else { return }
                    
                    if let error = error {
                        self.displayError(error)
                        return
                    }
                    
                    print("配置获取成功了")
                    let str = remoteConfig["adData"].stringValue
                    print(str)
                    
                    // 添加配置更新监听器
                    self.remoteConfig.addOnConfigUpdateListener { [weak self] configUpdate, error in
                        guard let self = self, error == nil else {
                            self?.displayError(error)
                            return
                        }
                        
                        print("Updated keys: \(configUpdate?.updatedKeys ?? [])")
                        // 这里可以根据需要处理更新的配置
                    }
                }
            } else {
                print("Remote config fetch failed with status: \(status)")
            }
        }
    }
    func displayError(_ error: Error?) {
        if let error = error {
            // 这里可以根据你的需求来处理错误
            // 例如，你可以将错误记录到日志系统，或者显示一个用户友好的错误消息
            print("Error occurred: \(error.localizedDescription)")
        } else {
            // 如果错误为nil，这里可以处理没有错误但想要通知用户的情况
            // 但在这个上下文中，它不太可能有用
            print("No error occurred.")
        }
    }
    
    func application(
        _ app: UIApplication,
        open url: URL,
        options: [UIApplication.OpenURLOptionsKey : Any] = [:]
    ) -> Bool {
        ApplicationDelegate.shared.application(
            app,
            open: url,
            sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
            annotation: options[UIApplication.OpenURLOptionsKey.annotation]
        )
    }
    
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
//        //正常进入首页 可以弹开屏广告
//        let userDefaults = UserDefaults.standard
//        let shouOpen = userDefaults.bool(forKey: "tostOpenAd")
//        if shouOpen {
//            self.shouldShowFixedView = true
//        }else{
//            self.shouldShowFixedView = false
//        }
        
    }
    
    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }
    
    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        //从后台进入程序
        //        if shouldShowFixedView {
        //
        //            let dialogFrame = CGRect(x: 0, y: 200, width: 270, height: 200)
        //            self.rewardedView = YLALodaingView(frame: dialogFrame, title: "续费", paymentMethod: "支付宝", paymentDescription: "请使用支付宝完成支付。")
        //            self.window?.addSubview(self.rewardedView)
        //            self.rewardedView.snp.makeConstraints { make in
        //                make.left.top.right.bottom.equalToSuperview()
        //            }
        //            self.rewardedView.onCancel = {
        //                // 执行取消操作
        //                AppOpenAdManager.shared.showAdIfAvailable()
        //                self.rewardedView.removeFromSuperview()
        //            }
        //        }
        
    }
    
    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    
    func checkIfCanMakePayments() -> Bool {
        return SKPaymentQueue.canMakePayments()
    }
    
    //恢复购买
    func renstorSet(){
        SwiftyStoreKit.restorePurchases(atomically: false) { results in
            if results.restoreFailedPurchases.count > 0 {
                print("Restore Failed: \(results.restoreFailedPurchases)")
                
            }else if results.restoredPurchases.count > 0 {
                
                for purchase in results.restoredPurchases {
                    if purchase.needsFinishTransaction {
                        SwiftyStoreKit.finishTransaction(purchase.transaction)
                    }
                    // 处理每个恢复的购买项目
                    self.handleRestoredPurchase(purchase)
                }
                print("Restore Success: \(results.restoredPurchases)")
                
            }else {
                print("Nothing to Restore")
                
                UserDefaults.standard.set(false, forKey: "life")
                UserDefaults.standard.set(false, forKey: "year")
                UserDefaults.standard.set(false, forKey: "week")
                
            }
        }
    }
    
    
    func handleRestoredPurchase(_ purchase: Purchase) {
        let productId = purchase.productId
        print("Restored Purchase: \(productId)")
        
        // 根据 productId 确定是订阅还是非消耗型产品
        if isSubscription(productId: productId) {
            // 处理订阅恢复
            print("Restored Subscription: \(productId)")
            restoreSubscription(purchase)
        } else {
            // 处理非消耗型产品恢复
            print("Restored Consumable or Non-Consumable Product: \(productId)")
            unlockNonConsumableContent(purchase)
        }
    }

    func isSubscription(productId: String) -> Bool {
        // 判断是否为订阅产品，通常根据产品ID的命名规则
        let subscriptionProductIds: Set<String> = ["com.aichat.yourloverai.ailoveryour.yearly001","com.nexthinks.yourloverai.weekly001"]
        return subscriptionProductIds.contains(productId)
    }

    func restoreSubscription(_ purchase: Purchase) {
        // 恢复订阅内容或状态
        print("Restoring subscription for product: \(purchase.productId)")
        // 根据你的业务逻辑处理订阅恢复
        self.validateReceipt([purchase.productId])
    }

    func unlockNonConsumableContent(_ purchase: Purchase) {
        // 解锁用户已经购买的非消耗型产品内容
        print("Unlocking content for product: \(purchase.productId)")
        // 根据你的业务逻辑解锁相应的内容
        self.verifyPurchase(purchase.productId)
    }
    
    
    //订阅校验
    func validateReceipt(_ productIds: Set<String>) {
        let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: "ad1b36f7462843a0be8aee1da39b1b4a")
        SwiftyStoreKit.verifyReceipt(using: appleValidator) { result in
            
            switch result {
            case .success(let receipt):
                let purchaseResult = SwiftyStoreKit.verifySubscriptions(productIds: productIds, inReceipt: receipt)
                self.alertForVerifySubscriptions(purchaseResult, productIds: productIds)
            case .error: break
                
            }
        }
    }
    
    
    //一次性买断校验
    func verifyPurchase(_ productId: String) {
        
        let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: "ad1b36f7462843a0be8aee1da39b1b4a")
        SwiftyStoreKit.verifyReceipt(using: appleValidator) { result in
            
            switch result {
            case .success(let receipt):
                let purchaseResult = SwiftyStoreKit.verifyPurchase(
                    productId: productId,
                    inReceipt: receipt)
                self.alertForVerifyPurchase(purchaseResult, productId: productId)
            case .error: break
            
            }
        }
    }
    
    
    


    //成功
    func alertForVerifySubscriptions(_ result: VerifySubscriptionResult, productIds: Set<String>) -> Void {
        
        /*
         UserDefaults.standard.set(true, forKey: "life")
         UserDefaults.standard.set(true, forKey: "year")
         UserDefaults.standard.set(true, forKey: "week")
         */
        switch result {
        case .purchased(let expiryDate, let items):
            
            if items.first?.productId == "com.aichat.yourloverai.ailoveryour.yearly001"  {
                UserDefaults.standard.set(true, forKey: "year")
            }else{
                UserDefaults.standard.set(true, forKey: "week")
            }
            print("\(productIds) is valid until \(expiryDate)\n\(items)\n")
            //产品有效期至
            print("产品有效")
            
        case .expired(let expiryDate, let items):
            print("\(productIds) is expired since \(expiryDate)\n\(items)\n")
            
            if items.first?.productId == "com.aichat.yourloverai.ailoveryour.yearly001"  {
                UserDefaults.standard.set(false, forKey: "year")
            }else{
                UserDefaults.standard.set(false, forKey: "week")
            }
        
            print("已过期")
        case .notPurchased:
            
            
            
            //到期  存储标识符
            print("没有购买过")
            print("\(productIds) has never been purchased")
        }
    }
    
    
    //固定商品一次性买断
    func alertForVerifyPurchase(_ result: VerifyPurchaseResult, productId: String) -> Void {
        
        switch result {
        case .purchased:
            
            UserDefaults.standard.set(true, forKey: "life")
            print("\(productId) is purchased")
            
        case .notPurchased:
            
            UserDefaults.standard.set(false, forKey: "life")
            print("\(productId) has never been purchased")
        }
    }
    
}



